import 'package:flutter/material.dart';
import '../view/mine_top_view.dart';
import '../../manger/user_manger.dart';
import 'package:ninetyfour/l10n/app_localizations.dart';
import '../controller/account_ye.dart';
import '../controller/mycoupon_page.dart';
import '../../services/yh_info_manger.dart'; 
import '../controller/security_page.dart';
import '../controller/account_chong.dart';
import '../controller/set_page.dart';

import 'package:ninetyfour/main.dart'; // 确保导入routeObserver
import '../../services/global_state.dart';
import 'package:provider/provider.dart';
import '../../components/toast_utils.dart';
import '../../login/controller/login_view.dart';

class ProfilePage extends StatefulWidget {
  const ProfilePage({super.key});

  @override
  _ProfilePageState createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> with AutomaticKeepAliveClientMixin, RouteAware {
  final GlobalKey<MineTopViewState> _mineTopViewKey = GlobalKey<MineTopViewState>();
  final List<String> linesList = [
    "AccountBalance",
    "Coupon",
    "AccountSecurity",
    "Account",
    "Set"
  ];
  int couponNum = 0;

  @override
  void initState() {
    super.initState();
    _loadUserInfos();
    _loadCouponCount();
  }


  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    final route = ModalRoute.of(context);
    if (route is PageRoute) {
      routeObserver.subscribe(this, route);
    }
  }

  @override
  void dispose() {
    routeObserver.unsubscribe(this);
    super.dispose();
  }

  @override
  void didPush() {
    // 页面被推入时调用
  }

  @override
  void didPopNext() {
    // 从其他页面返回时调用
    _loadUserInfos();
    _loadCouponCount();
  }

  Future<void> _loadCouponCount() async {
    final result = await MyCouponManger().loadDiscountData(0);
    if (result.success && result.myCoupon != null && mounted) {
      setState(() {
        couponNum = result.myCoupon!.length;
      });
      Provider.of<GlobalState>(context, listen: false).updateNotificationCount(result.myCoupon!.length);
    }
  }

  bool get wantKeepAlive => true;

  void _loadUserInfos() async {
    // WidgetsBinding.instance.addPostFrameCallback((_) {
    //   ToastUtils.showLoadingToast(context);
    // });

    await UserInfos.shared.checkAccount();

    _mineTopViewKey.currentState?.updateUserState();

    // WidgetsBinding.instance.addPostFrameCallback((_) {
    //   ToastUtils.dismissLoadingToast();
    // });
  }


@override
Widget build(BuildContext context) {
  super.build(context); // 保持自动保持状态生效
  return Scaffold(
    body: Column(
      children: [
        SizedBox(
          height: 200,
          child: MineTopView(
            key: _mineTopViewKey,
            onTap: () {
              Navigator.push(context, MaterialPageRoute(builder: (_) => const LoginView()));
            },
          ),
        ),
        Padding(
            padding: const EdgeInsets.symmetric(horizontal: 15),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(12),
              child: build2(context),
            ),
          ),
      ],
    ),
  );
}

Widget build2(BuildContext context) {
  return Container(
    color: Colors.white,
    padding: const EdgeInsets.symmetric(horizontal: 15),
    child: ListView.builder(
      physics: const NeverScrollableScrollPhysics(),
      shrinkWrap: true,
      padding: EdgeInsets.zero,
      itemCount: linesList.length,
      itemBuilder: (context, index) {
        return GestureDetector(
          onTap: () {
            Widget page;
            switch (index) {
              case 0:
                page = const AccountYePage();
                break;
              case 1:
                page = const MyCouponPage();
                break;
              case 2:
                page = const SecurityPage();
                break;
              case 3:
                page = const AccountChongPage();
                break;
              case 4:
                page = SetPage();
                break;
              default:
                return;
            }
            Navigator.push(context, MaterialPageRoute(builder: (_) => page));
          },
          child: MineListItem(
            title: linesList[index],
            showVersion: index == 2,
            couponNum: index == 1 ? couponNum : 0,
            isLast: index == linesList.length - 1,
          ),
        );
      },
    ),
  );
}


  Widget _buildLoadingView() {
    return const Center(
      child: Padding(
        padding: EdgeInsets.all(20),
        child: CircularProgressIndicator(),
      ),
    );
  }

}


class MineListItem extends StatelessWidget {
  final String title;
  final bool showVersion;
  final int couponNum;
  final bool isLast;

  const MineListItem({
    Key? key,
    required this.title,
    this.showVersion = false,
    this.couponNum = 0,
    this.isLast = false,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final localizations = AppLocalizations.of(context)!;
    return Container(
      height: 65, 
      padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 20),
      decoration: BoxDecoration(
        // 修改分割线样式
        border: isLast
            ? Border()
            : Border(
                bottom: BorderSide(
                  color: Color(0xFFF0F0F0), // 设置分割线颜色为 #F0F0F0
                  width: 1,
                ),
              ),
      ),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Row(
                children: [
                  Image.asset("assets/images/$title.png", width: 22, height: 22),
                  const SizedBox(width: 10),
                  Text(
                    localizations.getString(title),
                    style: const TextStyle(fontSize: 14, color: Color(0xFF4C4C4C)),
                  ),
                ],
              ),
              Row(
                children: [
                  if (showVersion)
                    Container(
                      padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 2),
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        color: Colors.red.shade100,
                        borderRadius: BorderRadius.circular(13),
                      ),
                      child: Text(
                        localizations.safetyLevel,
                        style: TextStyle(fontSize: 12, color: Colors.red),
                      ),
                    ),
                  if (couponNum > 0)
                    Container(
                      // 固定宽度和高度都为 22
                      width: 22,
                      height: 22,

                      decoration: BoxDecoration(
                        color: Colors.red,
                        // 设置为圆形
                        borderRadius: BorderRadius.circular(11),
                      ),
                      // 让文本在容器中居中
                      alignment: Alignment.center,
                      child: Text(
                        "$couponNum",
                        style: const TextStyle(fontSize: 14, color: Colors.white),
                      ),
                    ),
                  const SizedBox(width: 10),
                  Image.asset("assets/images/mineicon.png", width: 14, height: 14),
                ],
              ),
            ],
          ),
          // 添加分割线的偏移

        ],
      ),
    );
  }
}